using GrapeCity.Forguncy.Commands;
using GrapeCity.Forguncy.Plugin;
using GrapeCity.Forguncy.Log;
using System;
using System.ComponentModel;
using System.Threading.Tasks;
using TextEmbedding.Core;
using System.Collections.Generic;

namespace TextEmbedding
{
    [Icon("pack://application:,,,/TextEmbedding;component/Resources/Icon.png")]
    [Category("分词与向量化")]
    [OrderWeight(100)]
    public class Tokenize : Command, ICommandExecutableInServerSideAsync, IServerCommandParamGenerator
    {
        [FormulaProperty]
        [DisplayName("被分词的文本")]
        [OrderWeight(1)]
        public object TextExpr { get; set; }

        [BoolProperty]
        [DisplayName("是否为全分词模式")]
        [OrderWeight(10)]
        public bool IsCutAll { get; set; }


        [ResultToProperty]
        [DisplayName("分词的结果数组")]
        [OrderWeight(99)]
        public string ResultTo { get; set; } = "StringArray";

        public async Task<ExecuteResult> ExecuteAsync(IServerCommandExecuteContext dataContext)
        {
            var text = (await dataContext.EvaluateFormulaAsync(TextExpr))?.ToString() ?? "";

            if (string.IsNullOrWhiteSpace(text))
            {
                throw new Exception("文本不能为空");
            }

            var result = ZhTokenizer.Tokenize(text, IsCutAll);

            if (!string.IsNullOrEmpty(ResultTo))
            {
                dataContext.Parameters[ResultTo] = result;  // 把计算的结果设置到结果变量中
            }
            else
            {
                dataContext.Log.AppendLine($"分词完成，数量为{result}，但没有设置返回值，结果被丢弃。");
            }

            return new ExecuteResult();
        }

        public override string ToString()
        {
            return "中文分词";
        }

        public override CommandScope GetCommandScope()
        {
            return CommandScope.ExecutableInServer;
        }

        public IEnumerable<GenerateParam> GetGenerateParams()
        {
            yield return new GenerateListParam()
            {
                ParamName = this.ResultTo,
                Description = "分词结果",
                ParamScope = CommandScope.All
            };
        }
    }
}
